<template>
  <div class="fill-template-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="templateInfo?.name || '填写模板'"
      left-arrow
      @click-left="$router.back()"
      fixed
    >
      <template #right>
        <van-button size="small" @click="previewTemplate">预览</van-button>
      </template>
    </van-nav-bar>

    <div class="page-content">
      <!-- 模板信息 -->
      <div v-if="templateInfo" class="template-info">
        <div class="info-header">
          <div class="template-name">{{ templateInfo.name }}</div>
          <div class="template-category">{{ templateInfo.category }}</div>
        </div>
        
        <!-- 填写指南 -->
        <div v-if="templateInfo.fillGuide" class="fill-guide">
          <div class="guide-title">📝 填写指南</div>
          <div class="guide-content">{{ templateInfo.fillGuide }}</div>
        </div>

        <!-- 必备材料提醒 -->
        <div v-if="templateInfo.evidenceList && templateInfo.evidenceList.length > 0" class="evidence-reminder">
          <div class="reminder-title">📋 请准备以下材料</div>
          <div class="evidence-checklist">
            <van-checkbox-group v-model="checkedEvidence">
              <van-checkbox
                v-for="(evidence, index) in templateInfo.evidenceList"
                :key="index"
                :name="evidence"
                shape="square"
              >
                {{ evidence }}
              </van-checkbox>
            </van-checkbox-group>
          </div>
        </div>
      </div>

      <!-- 填写表单 -->
      <div class="fill-form">
        <div class="form-title">📄 模板填写</div>
        
        <!-- 动态表单字段 -->
        <van-form @submit="onSubmit" ref="formRef">
          <div
            v-for="field in formFields"
            :key="field.key"
            class="form-field"
          >
            <van-field
              v-if="field.type === 'input'"
              v-model="formData[field.key]"
              :name="field.key"
              :label="field.label"
              :placeholder="field.placeholder"
              :rules="field.rules"
              required
            />
            
            <van-field
              v-else-if="field.type === 'textarea'"
              v-model="formData[field.key]"
              :name="field.key"
              :label="field.label"
              :placeholder="field.placeholder"
              :rules="field.rules"
              type="textarea"
              rows="3"
              autosize
              required
            />
            
            <van-field
              v-else-if="field.type === 'date'"
              v-model="formData[field.key]"
              :name="field.key"
              :label="field.label"
              :placeholder="field.placeholder"
              readonly
              @click="showDatePicker(field.key)"
              required
            />
            
            <van-field
              v-else-if="field.type === 'select'"
              v-model="formData[field.key]"
              :name="field.key"
              :label="field.label"
              :placeholder="field.placeholder"
              readonly
              @click="showPicker(field.key, field.options)"
              required
            />
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="submitting"
            >
              生成文档
            </van-button>
          </div>
        </van-form>
      </div>
    </div>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePickerPopup" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onDateConfirm"
        @cancel="showDatePickerPopup = false"
      />
    </van-popup>

    <!-- 选项选择器 -->
    <van-popup v-model:show="showPickerPopup" position="bottom">
      <van-picker
        :columns="pickerColumns"
        @confirm="onPickerConfirm"
        @cancel="onPickerCancel"
      />
    </van-popup>

    <!-- 预览弹窗 -->
    <van-popup
      v-model:show="showPreview"
      position="bottom"
      :style="{ height: '80%' }"
      round
      closeable
    >
      <div class="preview-content">
        <div class="preview-header">
          <div class="preview-title">文档预览</div>
          <div class="preview-actions">
            <van-button size="small" @click="copyContent">复制</van-button>
            <van-button size="small" type="primary" @click="downloadDoc">下载</van-button>
          </div>
        </div>
        <div class="preview-body">
          <div class="document-content">{{ generatedContent }}</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'

const route = useRoute()
const router = useRouter()

// 响应式数据
const templateInfo = ref(null)
const formData = reactive({})
const formFields = ref([])
const checkedEvidence = ref([])
const submitting = ref(false)
const showDatePickerPopup = ref(false)
const showPickerPopup = ref(false)
const showPreview = ref(false)
const currentDate = ref(new Date())
const currentFieldKey = ref('')
const pickerColumns = ref([])
const generatedContent = ref('')
const formRef = ref()

// 模拟模板数据
const mockTemplate = {
  id: 1,
  name: '劳动仲裁申请书',
  category: '职场纠纷',
  description: '用于申请劳动仲裁的标准模板',
  fillGuide: '请按照提示填写相应信息。公司全称可通过企查查等平台查询确认。拖欠金额需要有明确的计算依据。',
  evidenceList: ['劳动合同', '工资流水', '考勤记录', '工作证明', '身份证复印件'],
  content: `劳动仲裁申请书

申请人：[姓名]，性别：[性别]，年龄：[年龄]岁
住址：[住址]
联系电话：[电话]

被申请人：[公司全称]
住所地：[公司地址]
法定代表人：[法人姓名]
联系电话：[公司电话]

仲裁请求：
1. 请求被申请人支付申请人工资[拖欠金额]元；
2. 请求被申请人支付申请人经济补偿金[补偿金额]元；
3. 本案仲裁费用由被申请人承担。

事实和理由：
[详细描述]

此致
[所在地]劳动人事争议仲裁委员会

申请人：[签名]
[申请日期]`,
  fields: [
    {
      key: 'name',
      label: '姓名',
      type: 'input',
      placeholder: '请输入您的姓名',
      rules: [{ required: true, message: '请输入姓名' }]
    },
    {
      key: 'gender',
      label: '性别',
      type: 'select',
      placeholder: '请选择性别',
      options: ['男', '女'],
      rules: [{ required: true, message: '请选择性别' }]
    },
    {
      key: 'age',
      label: '年龄',
      type: 'input',
      placeholder: '请输入年龄',
      rules: [{ required: true, message: '请输入年龄' }]
    },
    {
      key: 'address',
      label: '住址',
      type: 'textarea',
      placeholder: '请输入详细住址',
      rules: [{ required: true, message: '请输入住址' }]
    },
    {
      key: 'phone',
      label: '联系电话',
      type: 'input',
      placeholder: '请输入联系电话',
      rules: [{ required: true, message: '请输入联系电话' }]
    },
    {
      key: 'companyName',
      label: '公司全称',
      type: 'input',
      placeholder: '请输入公司全称',
      rules: [{ required: true, message: '请输入公司全称' }]
    },
    {
      key: 'companyAddress',
      label: '公司地址',
      type: 'textarea',
      placeholder: '请输入公司地址',
      rules: [{ required: true, message: '请输入公司地址' }]
    },
    {
      key: 'legalPerson',
      label: '法定代表人',
      type: 'input',
      placeholder: '请输入法定代表人姓名',
      rules: [{ required: true, message: '请输入法定代表人' }]
    },
    {
      key: 'companyPhone',
      label: '公司电话',
      type: 'input',
      placeholder: '请输入公司联系电话',
      rules: [{ required: true, message: '请输入公司电话' }]
    },
    {
      key: 'owedAmount',
      label: '拖欠金额',
      type: 'input',
      placeholder: '请输入拖欠工资金额（元）',
      rules: [{ required: true, message: '请输入拖欠金额' }]
    },
    {
      key: 'compensationAmount',
      label: '经济补偿金',
      type: 'input',
      placeholder: '请输入经济补偿金金额（元）',
      rules: [{ required: true, message: '请输入补偿金额' }]
    },
    {
      key: 'description',
      label: '详细描述',
      type: 'textarea',
      placeholder: '请详细描述劳动关系、工作内容、拖欠工资情况等',
      rules: [{ required: true, message: '请输入详细描述' }]
    },
    {
      key: 'location',
      label: '所在地',
      type: 'input',
      placeholder: '请输入所在地（如：北京市朝阳区）',
      rules: [{ required: true, message: '请输入所在地' }]
    },
    {
      key: 'signature',
      label: '签名',
      type: 'input',
      placeholder: '请输入您的签名',
      rules: [{ required: true, message: '请输入签名' }]
    },
    {
      key: 'applicationDate',
      label: '申请日期',
      type: 'date',
      placeholder: '请选择申请日期',
      rules: [{ required: true, message: '请选择申请日期' }]
    }
  ]
}

// 计算属性
const isFormValid = computed(() => {
  return formFields.value.every(field => {
    if (field.rules && field.rules.some(rule => rule.required)) {
      return formData[field.key] && formData[field.key].trim() !== ''
    }
    return true
  })
})

// 方法
const loadTemplate = async () => {
  const templateId = route.params.id
  
  // 模拟API请求
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 使用模拟数据
  templateInfo.value = mockTemplate
  formFields.value = mockTemplate.fields
  
  // 初始化表单数据
  formFields.value.forEach(field => {
    formData[field.key] = ''
  })
  
  // 设置默认申请日期为今天
  formData.applicationDate = formatDate(new Date())
}

const showDatePicker = (fieldKey) => {
  currentFieldKey.value = fieldKey
  showDatePickerPopup.value = true
}

const showPicker = (fieldKey, options) => {
  currentFieldKey.value = fieldKey
  // 确保选项格式正确，并处理可能的空值或非数组情况
  if (Array.isArray(options) && options.length > 0) {
    pickerColumns.value = options.map(option => ({
      text: String(option),
      value: String(option)
    }))
  } else {
    // 提供默认选项以防止错误
    pickerColumns.value = [
      { text: '请选择', value: '' }
    ]
  }
  showPickerPopup.value = true
}

const onDateConfirm = (value) => {
  // 处理日期选择器的确认事件
  try {
    if (value && Array.isArray(value.selectedValues) && value.selectedValues.length >= 3) {
      const [year, month, day] = value.selectedValues
      formData[currentFieldKey.value] = `${year}年${month}月${day}日`
    } else if (value instanceof Date) {
      formData[currentFieldKey.value] = formatDate(value)
    } else if (currentDate.value instanceof Date) {
      formData[currentFieldKey.value] = formatDate(currentDate.value)
    } else {
      formData[currentFieldKey.value] = formatDate(new Date())
    }
  } catch (error) {
    console.error('日期选择器错误:', error)
    formData[currentFieldKey.value] = formatDate(new Date())
  }
  showDatePickerPopup.value = false
}

const onPickerConfirm = (value) => {
  // 处理选择器的确认事件，兼容不同的返回格式
  try {
    if (value && value.selectedOptions && Array.isArray(value.selectedOptions) && value.selectedOptions.length > 0) {
      const option = value.selectedOptions[0]
      formData[currentFieldKey.value] = option.text || option.value || String(option)
    } else if (value && value.selectedValues && Array.isArray(value.selectedValues) && value.selectedValues.length > 0) {
      formData[currentFieldKey.value] = String(value.selectedValues[0])
    } else if (typeof value === 'string') {
      formData[currentFieldKey.value] = value
    } else if (value && typeof value === 'object' && (value.text || value.value)) {
      formData[currentFieldKey.value] = value.text || value.value
    } else {
      console.warn('选择器返回值格式不正确:', value)
      formData[currentFieldKey.value] = ''
    }
  } catch (error) {
    console.error('选择器确认事件错误:', error)
    formData[currentFieldKey.value] = ''
  }
  showPickerPopup.value = false
}

const onPickerCancel = () => {
  showPickerPopup.value = false
}

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
}

const generateContent = () => {
  let content = templateInfo.value.content
  
  // 替换模板中的占位符
  const replacements = {
    '[姓名]': formData.name,
    '[性别]': formData.gender,
    '[年龄]': formData.age,
    '[住址]': formData.address,
    '[电话]': formData.phone,
    '[公司全称]': formData.companyName,
    '[公司地址]': formData.companyAddress,
    '[法人姓名]': formData.legalPerson,
    '[公司电话]': formData.companyPhone,
    '[拖欠金额]': formData.owedAmount,
    '[补偿金额]': formData.compensationAmount,
    '[详细描述]': formData.description,
    '[所在地]': formData.location,
    '[签名]': formData.signature,
    '[申请日期]': formData.applicationDate
  }
  
  Object.keys(replacements).forEach(key => {
    content = content.replace(new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replacements[key] || key)
  })
  
  return content
}

const onSubmit = async () => {
  submitting.value = true
  
  try {
    // 模拟提交处理
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成文档内容
    generatedContent.value = generateContent()
    
    // 显示预览
    showPreview.value = true
    
    showSuccessToast('文档生成成功')
  } catch (error) {
    showToast('生成失败，请重试')
  } finally {
    submitting.value = false
  }
}

const previewTemplate = () => {
  if (!isFormValid.value) {
    showToast('请先完善表单信息')
    return
  }
  
  generatedContent.value = generateContent()
  showPreview.value = true
}

const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(generatedContent.value)
    showSuccessToast('内容已复制到剪贴板')
  } catch (error) {
    showToast('复制失败')
  }
}

const downloadDoc = () => {
  // 创建下载链接
  const blob = new Blob([generatedContent.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${templateInfo.value.name}.txt`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  showSuccessToast('文档下载成功')
}

onMounted(() => {
  loadTemplate()
})
</script>

<style scoped>
.fill-template-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.page-content {
  padding-top: 46px;
  padding-bottom: 20px;
}

.template-info {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.template-name {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
}

.template-category {
  font-size: 12px;
  padding: 2px 8px;
  background: #f0f9ff;
  color: #1989fa;
  border-radius: 4px;
}

.fill-guide {
  background: #f0f9ff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
}

.guide-title {
  font-size: 14px;
  font-weight: 600;
  color: #1989fa;
  margin-bottom: 8px;
}

.guide-content {
  font-size: 13px;
  color: #646566;
  line-height: 1.5;
}

.evidence-reminder {
  background: #fff7e6;
  border-radius: 8px;
  padding: 12px;
}

.reminder-title {
  font-size: 14px;
  font-weight: 600;
  color: #ff976a;
  margin-bottom: 12px;
}

.evidence-checklist {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.fill-form {
  background: white;
  padding: 16px;
}

.form-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
}

.form-field {
  margin-bottom: 16px;
}

.form-actions {
  margin-top: 24px;
}

.preview-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.preview-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.preview-body {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.document-content {
  font-size: 14px;
  line-height: 1.8;
  color: #323233;
  white-space: pre-line;
  font-family: 'SimSun', serif;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
</style>